home *** CD-ROM | disk | FTP | other *** search
- Path: news.umbc.edu!not-for-mail
- From: schlein@umbc.edu (Jonas J. Schlein)
- Newsgroups: comp.lang.c
- Subject: Re: start array at k, not 0
- Date: 4 Jan 1996 15:27:34 -0500
- Organization: University of Maryland Baltimore County
- Message-ID: <4chd7m$n54@umbc9.umbc.edu>
- References: <Pine.OSF.3.91.960104095358.22268B-100000@io.UWinnipeg.ca>
- NNTP-Posting-Host: f-umbc9.umbc.edu
- NNTP-Posting-User: schlein
-
- Bill Simpson <wsimpson@uwinnipeg.ca> wrote:
- |> I have come up with the following 2 methods that allow one to talk about
- |> an array that starts at element k rather than 0. E.g. 10 element array
- |> y[k] to y[k+10]. Both seem to work. Is this illusory? Is one of the
- |> 2 ways better (or a way I haven't mentioned)?
- |>
- |> These programs set up y[5] to y[14].
- |>
- |> Thanks very much for any comments.
-
- Let me guess...You didn't read the FAQ?
-
- |> /*method 1*/
- |> #include <stdio.h>
- |>
- |> int main(void)
- |> {
- |> int i, x[10];
- |> int* y;
- |> int offset=5; /*ie 1st index at 5, y[5]-y[14] */
- |> y=x-offset;
- |>
- |> printf("offset=%d\n",offset);
- |>
- |> for (i=offset;i<10+offset;i++)
- |> {
- |> y[i]=i;
- |> printf("%d\n",y[i]);
- |> }
- |> return 0;
- |> }
-
- This corresponds roughly to the FAQ question 6.17. It often works, but
- is not guaranteed to work and does not correspond to the C standard.
-
- |> /*method 2*/
- |> #include <stdio.h>
- |> #include <stdlib.h>
- |>
- |> int main(void)
- |> {
- |> int i;
- |> int* y;
- |> int offset=5;
- |> int n=10;
- |> y=malloc(n*sizeof(int));
- |>
- |> printf("offset=%d\n",offset);
- |>
- |> for (i=offset;i<n+offset;i++)
- |> {
- |> y[i]=i;
- |> printf("%d\n",y[i]);
- |> }
- |> return 0;
- |> }
-
- I chalk this up to either dumb luck or else your compiler allocates memory
- in some kind of block sizes which allows *this* particular program
- using *this* particular offset to work. You have allocated a dynamic
- block of storage that can be referenced only from y[0] to y[9]. Any
- indices other than these are in the realm of undefined behavior.
- --
- "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
-
- Jonas J. Schlein (schlein@gl.umbc.edu)
-